package com.hnas.common.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.common.orm.VerifyCode;
import com.hnas.common.service.dto.DTOVerifyCode;
import com.hnas.common.service.dto.search.DTOVerifyCodeSearch;
import com.hnas.common.service.mapper.VerifyCodeMapper;
import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.dao.PageBean;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.util.StringUtil;

@Component("verifyCodeDAO")
public class VerifyCodeDAOImpl extends BaseDaoImpl<VerifyCode> implements VerifyCodeDAO{

	public VerifyCodeDAOImpl() {
		super(VerifyCode.class);
	}

	@Override
	public VerifyCode saveOrUpdate(DTOVerifyCode dto) throws Exception {
		VerifyCode vo = null;
		if(dto != null){
			String id = dto.getId();
			if(StringUtil.isNotEmpty(id)){
				vo = this.find(id);
			}
			if(vo == null){//新增
				vo = new VerifyCode();
				BeanUtils.copyProperties(dto, vo);
				this.persist(vo);
			}else{//修改
				BeanUtils.copyProperties(dto, vo, new String[]{"createTime","creator"});
				this.merge(vo);
			}
		}
		return vo;
	}

	@Override
	public DTOPagedList<DTOVerifyCode> search(DTOVerifyCodeSearch criteria) {
		DTOPagedList<DTOVerifyCode> pageList = new DTOPagedList<DTOVerifyCode>();
		List<DTOVerifyCode> list = new ArrayList<DTOVerifyCode>();
		PageBean<VerifyCode> page = new PageBean<VerifyCode>();
		page.setPageNo(criteria.getPageNo());
		page.setPageSize(criteria.getPageSize());
		page.setTotalCount(criteria.getTotalCount());
		StringBuffer sb = new StringBuffer();
		List<Object> paras = new ArrayList<Object>();
		/*int j = 1;
		if(StringUtil.isNotEmpty(criteria.getPhoneNo())){
			sb.append(" and t.phoneNo = ?"+j++);
			paras.add(criteria.getPhoneNo().trim());
		}*/
		if(sb.length() > 0){
			sb.delete(0, 5);
			sb.insert(0, " from VerifyCode t where ");
		}else{
			sb.append(" from VerifyCode t ");
		}
		sb.append(" order by t.createTime ");
		page.setQuery(sb.toString());
		page.setQueryCount("select count(t.id) "+sb);
		this.queryByPage(page, paras.toArray());
		pageList.setPageNo(page.getPageNo());
		pageList.setPageSize(page.getPageSize());
		pageList.setTotalCount(page.getTotalCount());
		for(VerifyCode vo : page.getList()){
			DTOVerifyCode dto = new DTOVerifyCode();
			dto = VerifyCodeMapper.getInstance().mapToValue(vo);
			list.add(dto);
		}
		pageList.setList(list);
		return pageList;
	}

}
